<template>
  <div
    class="selectStudent"
    v-loading="gettingStuData"
    element-loading-text="数据加载中"
    element-loading-spinner="el-icon-loading"
  >
    <div class="fnBox">
      <el-select
        v-model="select"
        placeholder="请选择"
        popper-class="fnBox_DropDown"
        @change="selectClass"
      >
        <el-option
          v-for="item in options"
          :key="item.classID"
          :label="item.className"
          :value="item.className"
        >
        </el-option>
      </el-select>
    </div>
    <div style="height: 30px; width: 80%;">
      <el-switch
        v-model="isFilterStu"
        active-text="我指导的学生"
        inactive-text="查看其他学生" @change="changeFilterStu">
      </el-switch>
    </div>
    <div class="searchInput">
      <el-input
        placeholder="姓名/学号"
        suffix-icon="el-input__icon el-icon-search"
        v-model="search"
      >
      </el-input>
    </div>
    <div class="taskStateSelect">
      <!-- <div
        :class="{
          reviewed: item.value === '已批',
          notReviewed: item.value === '未批',
          underReview: item.value === '在批',
          'reviewed-active':
            item.value === '已批' && selectReviewState === item.value,
          'notReviewed-active':
            item.value === '未批' && selectReviewState === item.value,
          'underReview-active':
            item.value === '在批' && selectReviewState === item.value,
        }"
        v-for="(item, index) in reviewStateOptions"
        :key="index"
        @click="handleSelectTaskState(item.value)"
      >
        {{ item.label }}({{getSelectClass(getReviewStateStu(finishedTaskStus, item.value), select).length }})
      </div> -->

      <el-select v-model="selectReviewState" placeholder="请选择批阅状态">
        <el-option
          v-for="item in reviewStateOptions"
          :key="item.value"
          :label="item.value + ` (${getSelectClass(getReviewStateStu(finishedTaskStus, item.value), select).length})人`"
          :value="item.value">
          <span style="float: left">{{ item.label }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ getSelectClass(getReviewStateStu(finishedTaskStus, item.value), select).length }} 人</span>
        </el-option>
      </el-select>
    </div>
    <div class="studentListBox">
      <div
        class="studentList"
        :style="{
          'min-height': newFinishTaskStuList.length ? '90px' : '120px',
        }"
        :class="{
          notAutoFlex:
            !newFinishTaskStuList.length || fullList.indexOf(0) == -1,
        }"
      >
        <div class="finishedStus" v-if="finishedTaskStus.length">
          <div />
          <div v-if="getSelectClass(finishedTaskStus, select).length">已学学生 {{ getSelectClass(finishedTaskStus, select).length +'/'+ getSelectClass(studentList, select).length}}</div>
            <img src="@/assets/images/full.png" class="imgIcon" @click="handleFull(0)" alt="放大" v-if="fullList.indexOf(0) == -1" />
            <img src="@/assets/images/outFull.png" class="imgIcon" @click="handleFull(0)" alt="缩小" v-else />
        </div>
        <div style="text-align: center;" class="showHeadTips" v-else>无已学学生</div>
        <div class="learnedHead">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            :disabled="!newFinishTaskStuList.length"
            >全选</el-checkbox
          >
          <!-- <el-select
            v-model="selectReviewState"
            placeholder="请选择"
            popper-class="learnedHead_DropDown"
          >
            <el-option
              v-for="item in reviewStateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select> -->
          <span :title="checkedStus.length+'/'+newFinishTaskStuList.length">
            {{ (checkedStus.length > newFinishTaskStuList.length ? newFinishTaskStuList.length : checkedStus.length) +'/'+ newFinishTaskStuList.length}}</span
          >
          <!-- <span style="min-width:28px">{{selectReviewState}}</span> -->
        </div>
        <div class="learnedHead learnedHead-other">
          <button
            class="confirmReview-default confirmReview-email"
            :class="{ 'confirmReview-email-confirm': newFinishTaskStuList.length }"
            @click="handleSendEmail(newFinishTaskStuList)"
            :disabled="!newFinishTaskStuList.length"
            v-loading="sendEmailLoading"
            element-loading-spinner="el-icon-loading"
          >
            发送邮件
          </button>
          <button
            class="confirmReview-default"
            :class="{ 'confirmReview-confirm': checkedStus.length }"
            @click="handleConfirmStus"
            :disabled="!checkedStus.length"
            v-loading="confirmLoading"
            element-loading-spinner="el-icon-loading"
          >
            批阅
          </button>
        </div>

        <div class="showHeadTips" v-if="!newFinishTaskStuList.length">
          {{ gettingStuData ? "数据加载中" : `无${selectReviewState}学生` }}
          <!-- <loading
            :loading="gettingStuData"
            :value="`无${selectReviewState}学生`"
          /> -->
        </div>
        <div class="list" v-if="newFinishTaskStuList.length">
          <el-checkbox-group
            v-model="checkedStus"
            @change="handleCheckedCitiesChange"
          >
            <el-tooltip class="item" effect="dark" :content="item.stuNum ||'无学号'" placement="top-start" v-for="(item, index) in newFinishTaskStuList" :key="index">

            <el-checkbox
              
              :label="item"
              :key="index"
              :class="{
                notReviewed:
                  checkStuCurrTaskState(item.userID) == '未批',
                reviewed: checkStuCurrTaskState(item.userID) == '已批',
                underReview:
                  checkStuCurrTaskState(item.userID) == '在批',
              }"
              >{{ item | filterUserName }}</el-checkbox
            >
            </el-tooltip>
          </el-checkbox-group>
        </div>
      </div>
      <div
        class="studentList"
        :class="{
          notAutoFlex: !nStudyingTaskStus.length || fullList.indexOf(1) == -1,
        }"
      >
        <div class="showHeadTips" v-if="!nStudyingTaskStus.length">
          <!-- <loading :loading="gettingStuData" :value="'无在学学生'" /> -->
          {{ gettingStuData ? "数据加载中" : "无在学学生" }}
        </div>
        <div class="studyingHead" v-if="nStudyingTaskStus.length">
          <div />
          <div>
            在学学生 {{ getSelectClass(nStudyingTaskStus, select).length + "/" + getSelectClass(studentList, select).length }}
          </div>
          <img src="@/assets/images/full.png" class="imgIcon" @click="handleFull(1)" alt="放大" v-if="fullList.indexOf(1) == -1" />
          <img src="@/assets/images/outFull.png" class="imgIcon" @click="handleFull(1)" alt="缩小" v-else />
        </div>
        <div class="sendBtnTool">
          <button
            class="confirmReview-default confirmReview-email"
            :class="{ 'confirmReview-email-confirm': nStudyingTaskStus.length }"
            @click="handleSendEmail(nStudyingTaskStus)"
            :disabled="!nStudyingTaskStus.length"
            v-loading="sendEmailLoading"
            element-loading-spinner="el-icon-loading"
          >
            发送邮件
          </button>
        </div>
        <div class="list" v-if="nStudyingTaskStus.length">
          <div class="staticBox">
            <el-tooltip class="item" effect="dark" :content="item.stuNum ||'无学号'" placement="top-start" v-for="(item, index) in nStudyingTaskStus" :key="index">
              <div
                class="staticInfo"
              >
                  <div class="circular" />
                  <div>
                    {{ item | filterUserName }}
                  </div>
              </div>
            </el-tooltip>
          </div>
        </div>
      </div>
      <div
        class="studentList"
        :class="{
          notAutoFlex: !nNotStartTaskStus.length || fullList.indexOf(2) == -1,
        }"
      >
        <div class="showHeadTips" v-if="!nNotStartTaskStus.length">
          {{ gettingStuData ? "数据加载中" : "无未学学生" }}
        </div>
        <div class="notStartHead" v-if="nNotStartTaskStus.length">
          <div />
          <div>
            未学学生 {{ getSelectClass(nNotStartTaskStus, select).length + "/" + getSelectClass(studentList, select).length }}
          </div>
          <img src="@/assets/images/full.png" class="imgIcon" @click="handleFull(2)" alt="放大" v-if="fullList.indexOf(2) == -1" />
          <img src="@/assets/images/outFull.png" class="imgIcon" @click="handleFull(2)" alt="缩小" v-else />
        </div>
        <div class="sendBtnTool">
          <button
            class="confirmReview-default confirmReview-email"
            :class="{ 'confirmReview-email-confirm': nNotStartTaskStus.length }"
            @click="handleSendEmail(nNotStartTaskStus)"
            :disabled="!nNotStartTaskStus.length"
            v-loading="sendEmailLoading"
            element-loading-spinner="el-icon-loading"
          >
            发送邮件
          </button>
        </div>
        <div class="list" v-if="nNotStartTaskStus.length">
          <div class="staticBox">
            <el-tooltip class="item" effect="dark" :content="item.stuNum ||'无学号'" placement="top-start" v-for="(item, index) in nNotStartTaskStus" :key="index">
            <div
              class="staticInfo"
              
              :key="index"
            >
              <div class="circular" />
              <div>
                {{ item | filterUserName }}
              </div>
            </div>
            </el-tooltip>
          </div>
        </div>
      </div>
    </div>
    <sendEmail :isShowDialog="isShowDialog" :studentList="sendEmailStuList"  @close="handleCloseSendEmailDialog" v-if="isShowDialog"/>
  </div>
</template>

<script>
import { getChooseNoData, getMultistudydata } from "@/request/teacher";
import {
  handleChangeTaskCommitJsonToArray,
  formatCourseGroupTaskObj,
} from "@/util/courseData";
// const loading = () => import("@/components/loading");
// import { a } from "@/util/testCourseData";
import { Session } from"@/util/sessionStorage.js"
import { mapState } from "vuex";
import testVue from '../../../../user/test.vue';
const sendEmail = ()=> import("@/views/teacher/taskReview/components/sendEmail")

export default {
  components: {
    // loading,
    sendEmail
  },
  data() {
    return {
      search: "",
      options: [
        {
          classID: 0,
          className: "全部班级",
        },
      ],
      select: "全部班级",

      reviewStateOptions: [
        // {
        //   value: "全部班级",
        //   label: "全部班级",
        // },
        {
          value: "已批",
          label: "已批",
        },
        {
          value: "在批",
          label: "在批",
        },
        {
          value: "未批",
          label: "未批",
        },
      ],
      selectReviewState: "",

      checkAll: false,
      checkedStus: [],
      isIndeterminate: true,

      nStudentList: [],
      // 学生课程的学习数据
      studentData: [],
      // 当前任务学生的学习数据
      studentTaskData: [],
      finishedTaskStus: [], // 已学学生列表
      studyingTaskStus: [], // 在学学生列表
      notStartTaskStus: [], // 未学学生列表
      fullList: [0], // 学生列表放大缩小
      gettingStuData: false,
      isGettingStudyData: false,
      confirmLoading: false, // 确认批阅
      sendEmailLoading: false, // 发送邮件
      isShowDialog: false,
      sendEmailStuList: [],
      isFilterStu: true, // 是否根据指导教师过滤学生
    };
  },
  props: {
    courseInfo: Object,
    studentList: Array,
    selectTaskInfo: Object,
    gettingStuList: Boolean,
  },
  watch: {
    selectTaskInfo(n) {
      this.initData();
      if (n.task) {
        this.handleFilterCurrTaskStus(n);
        // if (this.studentList) this.getCurrTaskStusData()
      }
      this.fullList = [0];
      this.selectReviewState = "未批";
      this.search = "";
    },
    studentList(n,o) {
      // if (n.length !== o.length) this.fetchStuStudyData();
      this.handleGetSessionStorageData()
      if (this.selectTaskInfo.task) {
        this.handleFilterCurrTaskStus(this.selectTaskInfo)
        // this.getCurrTaskStusData()
      }
    },
    courseInfo(n) {
      this.getCourseClass();
    },
    selectReviewState(n) {
      if (n) this.initData();
      // this.handleFilterCurrTaskStus(this.selectTaskInfo);
    },
    gettingStuList(n) {
      // if (!this.isGettingStudyData) {
      this.gettingStuData = n;
      // }
    },
    confirmLoading(n) {
      this.$emit("handleConfirmSelectStu", n);
    },
    // 班级列表数据加载后
    options(n) {
      this.handleSelectRouteClass();
    },
    // 检测路由已选的班级是否发生改变
    "$route.query"(n) {
      this.handleSelectRouteClass();
    },
  },
  filters: {
    filterUserName(value) {
      return (
        value.realName ||
        value.nickName ||
        value.email ||
        value.regName ||
        value.stuNum ||
        value.userID
      );
    },
  },
  computed: {
    ...mapState({
      classList: (state) => state.class.classList
    }),
    checkStuCurrTaskState() {
      return function (userID) {
        const getTaskGuideline = this.selectTaskInfo.task.data.guidelines.filter(item => item.operType !== "查阅")
        if (!getTaskGuideline.length) return "已批"

        const findStuData = this.studentList.find(
          (item) => item.userID === userID
        );
        if (findStuData) {
          const taskGroupID = this.getTaskGroupID;
          const taskID = this.getTaskID;
          const findTask = findStuData.finishedTaskResultArray?.find(item => item.taskID == taskID)
          if (!findTask) return "未批"
          return findTask.reviewState
        } else {
          return "未批";
        }
      };
    },
    // 获取选择的班级
    getSelectClass() {
      return function(arr, className) {
        if (className == "全部班级") return arr
        return arr.filter((item) =>
          this.checkStuClass(item.userID).some(
            (haveClassStu) =>
              haveClassStu.userID === item.userID &&
              (haveClassStu.className === className || this.filterUserInClass(haveClassStu.otherClassIDList, this.findCurrClass(className)))
          )
        );
      }
    },
    // 过滤出其他非常规课程的班级的学生
    filterUserInClass() {
      return function (otherClass, selectClassData) {
        if (otherClass && selectClassData) {
          return otherClass.split(',').map(item => Number(item)).some(item => item == selectClassData.classID)
        } else return false
      }
    },
    // 找到当前选择的班级信息 
    findCurrClass() {
      return function (className) {
        return this.options.find(item => item.className === className)
      }
    },
    // 获取指定学生的学习数据并且带班级
    checkStuClass() {
      return function (userID) {
        return this.studentList.filter(
          (item) => item.userID == userID && (item.className || item.otherClassIDList)
        );
      };
    },
    // 获取搜索的用户
    getSeachUser() {
      return function(arr, search) {
        return arr.filter((item) => {
          /**
           * 修复用户没有设置用户名时，导致用户被过滤
           */
          if (!item.realName && !item.nickName && !item.email && !item.regName && !item.stuNum) return true
          return (
            (item?.realName &&
              item?.realName?.indexOf(search) !== -1) ||
            (item?.stuNum && item?.stuNum?.indexOf(search) !== -1)
          );
        });
      }
    },
    // 获取批阅状态
    getReviewStateStu() {
      return function(arr, state) {
        return arr.filter((item) => {
          // if (this.checkedStus.some(citem => citem.userID == item.userID)) return true
          return this.checkStuCurrTaskState(item.userID) === state
          // const userTaskState = this.checkStuCurrTaskState(item.userID)
          // let isSelected = this.checkedStus.some(citem => citem.userID == item.userID)
          // if (state === "已批") {
          //   return userTaskState === "已批";
          // } else if (state === "在批") {
          //   return userTaskState === "在批" || (isSelected && (userTaskState === "已批"));
          // } else {
          //   return userTaskState === "未批" || (isSelected && (userTaskState === "在批"));
          // }
        });
      }
    },
    getTaskGroupID() {
      return this.selectTaskInfo.task.data.taskGroupID;
    },
    getTaskID() {
      return this.selectTaskInfo.task.data.taskID;
    },
    // 新的已学学生列表
    newFinishTaskStuList() {
       // 已学学生列表中 过滤班级
      let classArr = this.getSelectClass(this.finishedTaskStus,this.select)
      // 过滤用户
      let searchUser = this.getSeachUser(classArr, this.search)
      let selectState = this.getReviewStateStu(searchUser, this.selectReviewState)
      return selectState
    },
    // 新的在学学生列表
    nStudyingTaskStus() {
      // 在学学生列表中 过滤班级
      let classArr = this.getSelectClass(this.studyingTaskStus,this.select)
      // 过滤用户
      let searchUser = this.getSeachUser(classArr, this.search)
      return searchUser
    },
    // 新的未学学生列表
    nNotStartTaskStus() {
      // 未学学生列表中 过滤班级
      let classArr = this.getSelectClass(this.notStartTaskStus,this.select)
      // 过滤用户
      let searchUser = this.getSeachUser(classArr, this.search)
      return searchUser
    },
    sKey() {
      const {currNo, courseID } = this.$route.query
      return `${currNo}_${courseID}`
    }
  },
  created() {
    if (this.selectTaskInfo.task) {
      this.handleFilterCurrTaskStus(this.selectTaskInfo);
    }
    if (this.courseInfo.courseID) this.getCourseClass()
  },
  methods: {
    // 选择班级
    selectClass(value) {
      this.$emit("handleSelectClass", value)
    },
     // 定义一个函数用于获取学生学习数据
    async getStudentStudyDataBatched(params) {
      const batchSize = 5; // 指定每批获取的学生数量
      const totalStudents = params.userIDArray.length;
      const batches = Math.ceil(totalStudents / batchSize);

      let allData = [];

      // 分批次获取学生数据
      for (let i = 0; i < batches; i++) {
        const start = i * batchSize;
        const end = (i + 1) * batchSize;
        const batchUserIDs = params.userIDArray.slice(start, end);

        const batchParams = { ...params, userIDArray: batchUserIDs };

        try {
          // 调用获取学生学习数据的函数
          const batchData = await getMultistudydata(batchParams);
          batchData.forEach(item => {
            if (item.taskID === 360) {
              item.guidelineResults[1].submitContent.filePaths = []
            }
          })
          if (batchData) {
            allData = allData.concat(batchData);
          } else {
            console.error("获取学生的学习数据失败");
            return false;
          }
        } catch (error) {
          console.error("发生错误", error);
          return false;
        }
      }

      // 处理每个学生的guidelineResults
      allData.forEach(item => {
        if (item.guidelineResults) {
          Object.keys(item.guidelineResults).forEach(gkey => {
            item.guidelineResults[gkey].guidelineID = gkey;
          });
        }
      });

      // 执行格式化学生学习数据的函数
      this.formatStuStudyData(allData);

      return allData;
    },
    // 获取学生学习数据
    fetchMultistudydata(params) {
      this.handleChangeLoadingAnimation(true);
      // getChooseNoData()
      return new Promise((resolve, reject) => {
        if (!params.userIDArray.length) {
          this.handleChangeLoadingAnimation(false);
          return resolve([]);
        }
        if (params.chooseNo) {
          getChooseNoData({chooseNo: params.chooseNo}).then(res=> {
            if (res.data.error !== 0) {
              let taskgroup = res.data.taskGroupResults
              Object.keys(taskgroup).forEach(tgkey => {
                let taskResults = taskgroup[tgkey]?.taskResults
                Object.keys(taskResults).forEach(tkey => {
                  let guideline = taskResults[tkey]?.guidelineResults
                  if (guideline) {
                    Object.keys(guideline).forEach(gkey => {
                      guideline[gkey].guidelineID = gkey
                    })
                  }
                })
              })
              let data = [res.data.taskGroupResults?.[params.taskGroupID]?.['taskResults']?.[params.taskID]]
              if (data) {
                this.formatStuStudyData(data)
                resolve(data);
              } else resolve(false)
            }  else {
              this.$antdMessage.error({
                content: res.message || "获取学生的学习数据失败",
              });
              resolve(false);
            }
            this.handleChangeLoadingAnimation(false);
          })
        } else {
          // 调用分批获取学生学习数据的函数
          this.getStudentStudyDataBatched(params).then(success => {
            if (success) {
              console.log("成功获取并处理学生学习数据");
              resolve(success);
            } else {
              console.error("获取学生学习数据失败");
              this.$antdMessage.error({
                      content: "获取学生的学习数据失败",
                    });
                    resolve(false);
            }
            this.handleChangeLoadingAnimation(false);
          });

          // getMultistudydata(params).then((data) => {
          //   if (data) {
          //     data.forEach(item => {
          //       Object.keys(item.guidelineResults).forEach(gkey => {
          //         item.guidelineResults[gkey].guidelineID = gkey
          //       })
          //     })
          //     this.formatStuStudyData(data)
          //     resolve(data);
          //   } else {
          //     this.$antdMessage.error({
          //       content: "获取学生的学习数据失败",
          //     });
          //     resolve(false);
          //   }
          //   this.handleChangeLoadingAnimation(false);
          // });
        }
        this.gettingStuData = false;
      });
    },
    // 将学习数据存放在sessionStorage
    saveToSessionStorage(data) {
      const sKey = this.sKey;
      const sData = Session.get('stuStudyData') || {};

      // 获取已存在的数据
      const existingData = sData[sKey] || [];

      // 过滤掉已存在的学生数据
      const newData = data.filter(item => !existingData.some(ditem => ditem.userID === item.userID));

      // 合并新数据和已存在的数据
      const updatedData = [...existingData, ...newData];

      // 将数据分片存储
      const chunkSize = 5; // 指定每个分片的大小
      const chunks = Math.ceil(updatedData.length / chunkSize);

      for (let i = 0; i < chunks; i++) {
        const start = i * chunkSize;
        const end = (i + 1) * chunkSize;
        const chunk = updatedData.slice(start, end);

        // 使用唯一的键来保存每个分片
        const chunkKey = `${sKey}_chunk_${i}`;
        Session.set(chunkKey, chunk);
      }

      // 更新主键值
      sData[sKey] = updatedData;
      Session.set('stuStudyData', sData);
      Session.set('stuStudyDataTout', new Date().getTime() + 600000);
    },
    // // 将学习数据存放在sessionStorage
    // saveToSessionStorage(data) {
    //   const sKey = this.sKey
    //   const sData = Session.get('stuStudyData') || {}
    //   if (sData && sData[sKey]) {
    //     sData[sKey] = sData[sKey].filter(item => !data.some(ditem => ditem.userID == item.userID))
    //     sData[sKey] = [...sData[sKey], ...data]
    //   } else {
    //     sData[sKey] = data
    //   }
    //   Session.set('stuStudyData', sData)
    //   Session.set('stuStudyDataTout', new Date().getTime() + 600000)
    // },
    // 获取所有学生当前任务的学习数据
    getCurrTaskStusData() {
      const userList = this.finishedTaskStus
      this.handleGetStuStudyData(userList)
    },
    // 设置加载动画的参数 data -- type:Boolean
    handleChangeLoadingAnimation(data) {
      this.gettingStuData = data;
      // this.isGettingStudyData = data;
      this.$emit("loadingStuStudyData", data)
    },
    // 全选按钮
    handleCheckAllChange(val) {
      (this.fullList.indexOf(0) == -1) && this.fullList.push(0)
      this.checkedStus = val ? this.newFinishTaskStuList : [];
      this.isIndeterminate = false;
    },
    // 单独选择
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.newFinishTaskStuList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.newFinishTaskStuList.length;
    },
    // 找出当前任务的学生数据
    async handleFilterCurrTaskStus(selectTaskInfo) {
      const currTask = selectTaskInfo.task.data;
      const currTaskID = currTask.taskID;
      // 分类
      let finishedTaskStuArray = [];
      let studyingTaskStuArray = [];
      let notStartTaskStuArray = [];
      this.studentList.forEach((item) => {
        if (item.finishedTaskResultArray.some(sitem => sitem.taskID == currTaskID)) {
          finishedTaskStuArray.push(item);
        } else if (item.studyingTaskIDArray.indexOf(currTaskID) !== -1) {
          studyingTaskStuArray.push(item);
        } else {
          notStartTaskStuArray.push(item);
        }
      });

      this.finishedTaskStus = finishedTaskStuArray;
      this.studyingTaskStus = studyingTaskStuArray;
      this.notStartTaskStus = notStartTaskStuArray;
    },
    // 在已学任务列表中找到还没有获取学习数据的学生的ID
    async handleGetStuStudyData(getStuList) {
      const currTask = this.selectTaskInfo.task.data;
      const currTaskID = currTask.taskID;
      const userIDArray = getStuList;
      // 找出还没有学习数据的用户ID 获取学习数据
      const findUsers = userIDArray
        .filter(
          (item) =>
            !this.studentData.some((sitem) => {
              if(item.userID === sitem.userID) {
                const findTask = sitem.allTaskResultsInChooseNo?.find(fitem => fitem.taskID == currTaskID)
                if (findTask) return true
                else return false
              } else return false
            })
        )
      const findUserID = findUsers.map((item) => item.userID);
      if (findUserID.length) {
        const params = {
          currNo: Number(this.$route.query.currNo),
          userIDArray: findUserID,
          taskID: this.selectTaskInfo.task.data.taskID,
          taskGroupID: this.selectTaskInfo.task.data.taskGroupID,
          chooseNo: findUsers.length == 1 ? findUsers[0].chooseNo : undefined
        }
        await this.fetchMultistudydata(params);
      }

      // 查找已选的学生的学习数据
      const findSelectReviewStus = this.studentData
        .filter((item) =>
          userIDArray.some((user) => item.userID === user.userID)
        )
        .map(item => {
          const findTaskData = item.allTaskResultsInChooseNo?.find(fitem => fitem.taskID == currTaskID)
          if (findTaskData) {
            const newitem = Object.assign({}, findTaskData)
            newitem.userID = item.userID;
            newitem.stuNum = item.stuNum;
            newitem.name =
              item.realName ||
              item.nickName ||
              item.email ||
              item.regName ||
              item.stuNum ||
              `${"ID:" + item.userID}`;
            return newitem;
          } else {
            const { realName, nickName, email, regName, stuNum, userID } = item;
            return {
              notTaskData: true,
              name:
                realName ||
                nickName ||
                email ||
                regName ||
                stuNum ||
                `${"ID:" + userID}`,
              stuNum: stuNum,
              userID,
            };
          }
        });
      this.studentTaskData = findSelectReviewStus;
      this.$emit("changeStudentTaskData", this.studentTaskData);
    },
    // 确认选择学生
    async handleConfirmStus() {
      this.confirmLoading = true;
      await this.handleGetStuStudyData(this.checkedStus);
      this.$nextTick(() => {
        const timer = setTimeout(() => {
          this.confirmLoading = false;
          clearTimeout(timer);
        }, 250);
      });
    },
    // 发送邮件
    async handleSendEmail(arr) {
      this.sendEmailLoading = true
      this.sendEmailStuList = arr
      this.$nextTick(() => {
        const timer = setTimeout(() => {
          this.sendEmailLoading = false;
          this.isShowDialog = true
          clearTimeout(timer);
        }, 250);
      });
    },
    handleCloseSendEmailDialog() {
      this.isShowDialog = false
    },
    // 当前一次性加载所有学生的学习数据  todo 当学生列表发生改变时 请求一部分学生的学习数据
    async fetchStuStudyData(num = 5) {
      let numbers = num;
      let splitStuList = this.studentList.map((item) => item.userID);
      const times = Math.ceil((splitStuList.length / numbers))
      if (splitStuList.length) {
        for (let index = 0; index < times; index++) {
          const spliceList = splitStuList.splice(0, numbers)
          this.fetchMultistudydata({
            currNo: Number(this.$route.query.currNo),
            userIDArray: spliceList,
          });
        }
      }

      // if (this.selectReviewState !== '全部班级') {
      //   this.handleFilterCurrTaskStus(this.selectTaskInfo)
      // }
      // this.handleGetStuStudyData()
    },
    // 放大缩小
    handleFull(index) {
      if (this.fullList.indexOf(index) == -1) {
        this.fullList.push(index);
      } else {
        this.fullList = this.fullList.filter((i) => i !== index);
      }
    },
    // 初始化数据
    initData() {
      this.checkedStus = [];
      this.checkAll = false;
      this.isIndeterminate = false;
    },
    // 选择任务状态
    handleSelectTaskState(value) {
      if (this.selectReviewState === value) {
        this.selectReviewState = "";
      } else this.selectReviewState = value;
    },
    // 获取课程的班级
    async getCourseClass() {
      if (this.options.length == 1) {
        const classIDList = this.courseInfo?.classIDList?.split(',')?.map(i => Number(i)) || [];
        const classNameList = this.courseInfo.classNameList?.split(',') || [];
        let classList = (await this.$store.dispatch("class/gClassList")) || [];
        // 过滤重复的班级
        classList = classList.filter((item) => {
          return (
            !this.options.find((oitem) => oitem.classID == item.classID) &&
            ((classIDList && classIDList?.indexOf(item.classID) !== -1) ||
              (classNameList && classNameList?.indexOf(item.className) !== -1))
          );
        });
        this.options = [...this.options, ...classList];
      }
    },
    // 将路由中标记的班级选中
    handleSelectRouteClass() {
      const { query } = this.$route;
      if (query.filter) {
        const findClass = this.options.find((item) => item.className === query.filter);
        if (findClass) this.select = findClass.className == "全部" ? "全部班级": findClass.className;
      }
    },
    // 格式化学生的学习数据
    formatStuStudyData(data) {
      let changeDataUser = []
      data.forEach(item => {
        const findResultStuData = this.studentList.find(sitem => sitem.chooseNo == item.chooseNo)
        if (findResultStuData) {
          if (findResultStuData.allTaskResultsInChooseNo) {
            const isGeted = findResultStuData.allTaskResultsInChooseNo?.some(sitem => sitem.taskID == item.taskID)
            // 判断是否已经获取过数据了
            if (!isGeted) {
              findResultStuData.allTaskResultsInChooseNo.push(item)
            }
          } else {
            this.$set(findResultStuData, "allTaskResultsInChooseNo", [item])
          }
          changeDataUser.push(findResultStuData)
        }
      })
      const filterStudentData = this.studentData.filter(item => !changeDataUser.some(citem => citem.userID == item.userID))
      // studentData是所有获取过的学生的学习数据
      this.studentData = [...changeDataUser, ...filterStudentData];
      this.$emit("getStudentDataed", changeDataUser)
      this.saveToSessionStorage(this.studentData)
    },
    // 获取缓存中的学习数据
    async handleGetSessionStorageData() {
      const timeout = await Session.get("stuStudyDataTout");
      const currTime = new Date().getTime();
      if ((timeout - currTime) <= 0) return;

      const sKey = this.sKey;
      const sData = await Session.get("stuStudyData");

      if (!sData?.[sKey]) return;

      // 获取分片数据
      const chunkSize = 5; // 与保存时使用的分片大小相匹配
      const chunks = Math.ceil(sData[sKey].length / chunkSize);

      let arr = [];
      for (let i = 0; i < chunks; i++) {
        const chunkKey = `${sKey}_chunk_${i}`;
        const chunkData = await Session.get(chunkKey);

        if (chunkData) {
          arr = arr.concat(chunkData);
        } else {
          // 如果有任何一个分片不存在，则不继续处理
          return;
        }
      }

      const newStuList = this.studentList;

      // 更新学生数据
      this.studentData = newStuList.map(item => {
        const findStuData = arr.find(aitem => aitem.userID == item.userID);
        if (findStuData?.allTaskResultsInChooseNo) {
          this.$set(item, "allTaskResultsInChooseNo", findStuData.allTaskResultsInChooseNo);
        }
        return item;
      });
    },
    // // 获取缓存中的学习数据
    // async handleGetSessionStorageData() {
    //   const timeout = await Session.get("stuStudyDataTout")
    //   const currTime = new Date().getTime()
    //   if ((timeout - currTime) <= 0) return
    //   const sData = await Session.get("stuStudyData")
    //   const sKey = this.sKey
    //   if(!sData?.[sKey]) return
    //   const arr = sData[sKey]
    //   const newStuList = this.studentList
    //   this.studentData = newStuList.map(item => {
    //     const findStuData = arr.find(aitem => aitem.userID == item.userID)
    //     if (findStuData?.allTaskResultsInChooseNo) this.$set(item, "allTaskResultsInChooseNo", findStuData.allTaskResultsInChooseNo) 
    //     return item
    //   })
    // },
    changeFilterStu () {
      this.$emit('changeFilterStu', this.isFilterStu)
    }
  },
};
</script>

<style lang="stylus">
.selectStudent {
  margin-right: 20px;
  padding: 10px 10px;
  width: 200px;
  min-width: 165px;
  height: 746px;
  background-color: #ffffff;
  border-radius: 10px;

  .taskStateSelect {
    margin-top: 10px;
    position: sticky;
    top: 51px;
    background: #fff;
    z-index: 99;
    display: flex;
    justify-content: space-between;
    align-items: center;

    // div {
    //   cursor: pointer;
    //   padding: 3px 3px;
    //   border: 1px solid #c4d3dc;
    //   border-radius: 5px;
    //   color: #707070;
    // }

    .el-select {
      .el-input__inner {
        padding-left: 10px;
        height: 30px;
        font-size: inherit;
        font-family: Source Han Sans CN;
        color: rgba(112, 112, 112, 0.8);
      }

      .el-input__icon {
        line-height: 30px;
      }
    }

    .reviewed, .notReviewed, .underReview {
      transition: background-color 0.1s linear;
    }

    .reviewed {
      background-color: #91cd7480;
      border-color: #91cd7480;
    }

    .underReview {
      background-color: #f9c9579c;
      border-color: #f9c9579c;
    }

    .notReviewed {
      background-color: #b6b9e25e;
      border-color: #b6b9e25e;
    }

    .reviewed:hover {
      background-color: #91cd74;
      border-color: #91cd74;
    }

    .notReviewed:hover {
      background-color: #b6b9e2;
      border-color: #b6b9e2;
    }

    .underReview:hover {
      background-color: #f9c957;
      border-color: #f9c957;
    }

    .reviewed-active {
      background-color: #91cd74;
      border-color: #91cd74;
      color: #fff;
    }

    .notReviewed-active {
      background-color: #b6b9e2;
      border-color: #b6b9e2;
      color: #fff;
    }

    .underReview-active {
      background-color: #f9c957;
      border-color: #f9c957;
      color: #fff;
    }
  }

  .searchInput {
    .el-input__inner {
      padding-left: 10px;
      height: 30px;
      border-radius: 5px;
      border: solid 1px #c4d3dc;
    }

    .el-input__icon {
      line-height: 30px;
    }
  }

  .fnBox {
    margin-bottom: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .el-select {
      .el-input__inner {
        padding-left: 10px;
        height: 30px;
        font-size: 1rem;
        font-family: Source Han Sans CN;
        color: rgba(112, 112, 112, 0.8);
      }

      .el-input__icon {
        line-height: 30px;
      }
    }
  }

  .studentListBox {
    // margin-top: 7px;
    display: flex;
    flex-flow: column;
    height: calc(100% - 40px - 60px - 12px - 30px);

    .studentList {
      flex: 1;
      margin-top: 5px;
      padding: 0 10px;
      min-height: 31px;
      border-radius: 5px;
      border: solid 1px #c4d3dc;
      overflow-y: scroll;
      transition: flex 0.2s linear;

      .showHeadTips {
        height: 31px;
        line-height: 31px;
        font-size: 1rem;
        font-family: Source Han Sans CN;
        text-align: center;
      }

      .finishedStus {
        display: flex;
        align-items: center;
        justify-content: space-between;
        position: sticky;
        top: 0px;
        background: #fff;
        z-index: 99;
      }

      .confirmReview-default {
        cursor: not-allowed;
        width: 40px;
        min-width: 41px;
        height: 25px;
        background-color: rgba(111,111,111,0.3);
        border-radius: 5px;
        font-family: Source Han Sans CN;
        font-size: .9rem;
        color: #fff;
        border: none;

        .el-loading-spinner {
          margin-top: -10px;
        }
      }

      .confirmReview-email {
        width: auto;
      }

      .confirmReview-confirm {
        cursor: pointer;
        background-color: #003262;
      }

      .confirmReview-email-confirm {
        cursor: pointer;
        background-color: #f6ad35;
      }

      .learnedHead {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 30px;
        // border-bottom: solid 1px rgba(112, 112, 112, 0.4);
        background: #fff;
        position: sticky;
        top: 21px;
        z-index: 99;


        .finishTaskCount {
          font-size: 12px;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: pre;
        }

        .el-checkbox {
          .el-checkbox__input {
            .el-checkbox__inner {
              width: 18px;
              height: 18px;
              background-color: #ffffff;
              border: solid 4px #707070;
              border-radius: 50%;
              transition: border-color 0.1s linear;
              font-family: Source Han Sans CN;
            }
          }

          .is-checked {
            .el-checkbox__inner {
              border-color: #003262;
            }
          }

          .el-checkbox__label {
            padding-left: 3px;
            font-size: 14px;
          }
        }

        .el-select {
          max-width: 56px;

          .el-input__inner {
            padding-left: 10px;
            padding-right: 10px;
            height: 22px;
            color: #707070;
          }

          .el-select__caret {
            width: 15px;
          }

          .el-input__icon {
            line-height: 22px;
          }
        }

      }

      .learnedHead-other {
        top: 51px;
      }

      .imgIcon {
        cursor: pointer;
        object-fit: cover;
        width: 16px;
        height: 16px;
      }
      

      .studyingHead, .notStartHead {
        display: flex;
        justify-content: space-between;
        align-items: center;
        min-height: 28px;
        border-bottom: 1px solid #707070;
        background: #fff;
        position: sticky;
        top: 1px;
        z-index: 99;

        .imgIcon {
          cursor: pointer;
          object-fit: cover;
          width: 16px;
          height: 16px;
        }
      }

      .sendBtnTool {
        position: sticky;
        top: 28px;
        padding-top: 7px;
        padding-bottom: 5px;
        background: #fff;
      }

      .list {
        .el-checkbox-group {
          display: flex;
          flex-flow: column;
          align-items: flex-start;
          justify-content: flex-start;

          .el-checkbox {
            padding: 3px 4px;
            margin: 10px 7px 0 2px;
            width: 95%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 22px;
            border-radius: 40px;

            .el-checkbox__label {
              padding: 0;
              font-family: Source Han Sans CN;
              font-size: 1rem;
              color: #000000;
            }

            .el-checkbox__input {
              padding-top: 1px;
              margin-left: 5px;

              // height: 18px;
              .el-checkbox__inner {
                border: none;
                // width: 18px;
                // height: 18px;
                // background-color: #ffffff;
                // border: solid 4px #fff;
                // border-radius: 50%;
                // transition: border-color 0.1s linear;
                // font-family: Source Han Sans CN;
              }

              .el-checkbox__inner::after {
                left: 5px;
                top: 2px;
              }
            }

            .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
              background: #053386;
            }
          }

          .is-checked.reviewed, .is-checked.underReview, .is-checked.notReviewed {
            .el-checkbox__inner {
              border-color: #003262;
            }
          }

          .reviewed {
            background-color: #91cd74;
          }

          .underReview {
            background-color: #f9c957;
          }

          .notReviewed {
            background-color: #b6b9e2;
          }

          .el-checkbox:after {
            position: relative;
            content: ' ';
            width: 14px;
          }
        }

        .staticBox {
          display: flex;
          flex-flow: column;
          align-items: flex-start;
          justify-content: flex-start;

          .staticInfo {
            padding: 3px 4px;
            margin: 10px 7px 0 2px;
            width: 95%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 22px;
            border-radius: 40px;
            border: 1px solid #B6B9E2;
            font-family: Source Han Sans CN;
            font-size: 1rem;
            color: #000000;

            .circular {
              width: 18px;
              height: 18px;
              background-color: rgba(111, 111, 111, 0.3);
              border: solid 1px #B6B9E2;
              border-radius: 50%;
            }
          }

          .staticInfo:after {
            position: relative;
            content: ' ';
            width: 14px;
          }
        }
      }
    }

    .notAutoFlex {
      flex: 0;
      overflow: hidden;

      .list {
        display: none;
      }
    }

    .isFlexAll {
      flex: 1 !important;
    }

    .studentList::-webkit-scrollbar {
      cursor: pointer;
      width: 4px;
      height: 1px;
    }

    /* 定义滚动条的滑块的样式有圆角和阴影以及自定义的背景色 */
    .studentList::-webkit-scrollbar-thumb {
      -webkit-box-shadow: inset 0 0 1px rgba(195, 197, 198, 0.1);
      background: #ccc;
      border-radius: 10px;
    }

    /* 定义滚动条所在轨道的样式。有圆角和阴影以及淡色系的背景色 */
    .studentList::-webkit-scrollbar-track {
      -webkit-box-shadow: inset 0 0 1px rgba(195, 197, 198, 0.1);
      border-radius: 4px;
    }
  }
}

.fnBox_DropDown {
  .el-select-dropdown__item {
    font-family: Source Han Sans CN;
    color: rgba(112, 112, 112, 0.8);
  }
}

.learnedHead_DropDown {
  .el-select-dropdown__item {
    font-family: Source Han Sans CN;
    color: #707070;
  }
}
</style>